// pinia
import { defineStore } from 'pinia'
// axios
import $ajax from '@/util/ajax/http'

import { ElMessage, ElMessageBox } from 'element-plus'

// 定义Pinia组件
export const usePersonStore = defineStore('person', {
  // 属性
  state: () => ({
    form: {
      gid: -1,
      gname: '网格',
      gdesc: '网格信息描述',
      status: 1,
    },
    persons: [],
    dialogFormVisible: false,
  }),
  // 方法
  actions: {
    delGrid(index) {
      ElMessageBox.confirm(
        '系统将要删除网格：' + this.grids[index].gname + ' , 确定继续吗?',
        '系统删除数据警告！',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning',
        },
      )
        .then(async () => {
          const path = '/sys/g/del/' + this.grids[index].gid
          const { data: res } = await $ajax.delete(path)
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: 'Delete completed',
            })
            this.grids.splice(index, 1)
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: 'Delete canceled',
          })
        })
    },

    async modPerson() {
      const path = '/sys/p/mod'
      const { data: res } = await $ajax.put(path, this.form)
      if (res.code === 200) {
        this.openOrClose()
        ElMessage({
          message: '员工：' + this.form.name + '\t角色修改成功！',
          type: 'success',
        })
      }
    },
    /**
     * 打开窗口了，准备新增，gid=-1，标识新增
     */
    show4Add() {
      this.openOrClose()
      this.form.gid = -1
    },
    /**
     * 打开窗口了，准备编辑， 修改form，在form中填充旧数据
     */
    show4Mod(index) {
      this.openOrClose()
      this.form = this.persons[index]
    },

    async addGrid() {
      const path = '/sys/g/add'
      const { data: res } = await $ajax.post(path, this.form)
      if (res.code === 200) {
        this.form.gid = res.result
        this.grids.push(this.form)
        this.openOrClose()
        ElMessage({
          message: '网格：' + this.form.gname + '\t添加成功！',
          type: 'success',
        })
      }
    },

    save() {
      if (this.form.pid > 0) {
        this.modPerson()
      }
      console.log(this.form)
    },

    async findall() {
      const path = '/sys/p/find/by/null'
      const { data: res } = await $ajax.get(path)
      if (res.code === 200) {
        this.persons = res.result
      }
    },
    openOrClose() {
      this.dialogFormVisible = !this.dialogFormVisible
    },
  },
})
